package com.it.controller;


import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.it.common.R;
import com.it.pojo.User;
import com.it.service.UserService;


import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/admin")
public class UserController {
    @Autowired
    private UserService userService;

    // 登录功能入口
    @PostMapping("/login")
    public R<User> login(@RequestBody User user, HttpSession session) {
        String username = user.getUsername();
        String password = user.getPassword();

        if (username == null || password == null) {
            return R.error("账号或密码不能为空");
        }

        String encoded = MD5.create().digestHex(password);

        User dbUser = userService.lambdaQuery()
                .eq(User::getUsername, username)
                .eq(User::getPassword, encoded)
                .one();

        if (dbUser == null) {
            return R.error("账号或密码错误");
        }

        if ("inactive".equals(dbUser.getStatus())) {
            return R.error("该账号被禁用");
        }

        dbUser.setPassword(null);
        session.setAttribute("user", dbUser);
        return R.success(dbUser);
    }
    @RequestMapping("/logout")
    public R logout(HttpSession session) {
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}


